package org.yaac.client.util;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import com.google.gwt.user.client.ui.ListBox;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class ListBoxUtil {

	/**
	 * @param listBox
	 * @param selectAllVal
	 * @param items
	 */
	public static void resetItems(ListBox listBox, String selectAllVal, Collection<String> items) {
		// insert value into the first
		List<String> vals = new LinkedList<String>(items);
		vals.add(0, selectAllVal);
		
		addAll(listBox, vals, false);
	}
	
	/**
	 * @param listBox
	 * @param items
	 */
	public static void resetItems(ListBox listBox, Collection<String> items) {
		addAll(listBox, items, false);
	}
	
	/**
	 * @param listBox
	 * @param items
	 * @param append
	 */
	public static void addAll(ListBox listBox, Collection<String> items, boolean append) {
		if (!append) {
			listBox.clear();
		}
		
		for (String item : items) {
			listBox.addItem(item);
		}
	}
	
	/**
	 * @param listBox
	 * @return
	 */
	public static String selectedVal(ListBox listBox) {
		int index = listBox.getSelectedIndex();
		
		// index == -1 means nothing selected
		// index == 0 means select all
		return index <= 0 ? null : listBox.getValue(index);
	}
}
